const app = getApp();
Page({

  /**
   * 页面的初始数据
   */
  data: {
    totalMoney: 0,
    carts: []
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onShow: function (options) {
    this.getcarts();
  },

  getTotalMoney() {
    let sum = 0;
    for (let item of this.data.carts) {
      sum += item.specfoods[0].price * item.buyNum;
    }
    this.setData({
      totalMoney: sum.toFixed(2)
    })
  },

  delCart(e) {
    let carts = this.data.carts;
    let url = '/cart/delCart';
    let id = e.currentTarget.dataset.id;
    app.ajax(url,{id},res=>{
      
      let index = carts.findIndex(item=>{
        return item.item_id == id;
      })
      // 把删除的商品从购物车移除
      carts.splice(index, 1);
      this.setData({
        carts: carts
      })
      this.getTotalMoney();
    })
  },

  clearCart() {
    let url = '/cart/clearCart';
    app.ajax(url, null, res => {
      this.setData({
        showCart: false,
        cartNum: 0,
        carts: []
      })
    })
  },

  getcarts() {
    let url = '/cart/cartList';
    let data = {};
    app.ajax(url,data,res=> {
      
      this.setData({
        carts: res.list
      })
      this.getTotalMoney();
    })
  },

  // 去结算
  count() {
    let url = '/order/createOrder';
    let params = [];
    let carts = this.data.carts;
    for (let cart of carts) {
      params.push({
        id: cart.id,
        buyNum: cart.buyNum
      })
    }
    app.ajax(url, { carts: params }, res => {
      this.setData({
        cartNum: 0,
        carts: []
      })
      wx.showModal({
        content: res.msg,
        showCancel: false,
        success: (res) => {
          if (res.confirm) {
            wx.switchTab({
              url: '/pages/order/order'
            })
          }
        }
      })
    })
  }
})